package sdu.icat.pj.service;

import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sdu.icat.pj.base.BaseService;
import sdu.icat.pj.repository.SysUserRepository;
import sdu.icat.pj.support.SimpleSpecification;
import sdu.icat.sys.smodel.SysUser;

/**
 * @author ljh_2015
 *
 */
@Service("_sysUser")
public class SysUserService extends BaseService<SysUser>{
    
    @Autowired private SysUserRepository sysUserRepository;
    
    @Autowired private SysAuthorizeService sysAuthorizeService;
    
    @Transactional
    public SysUser saveOrUpdate(SysUser entity) {
	return sysUserRepository.saveAndFlush(entity);
    }
    
    @Transactional
    public SysUser delete(SysUser user) {
	sysUserRepository.delete(user);
	return user;
    }
    
    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    public SysUser queryById(Long id) {
	return sysUserRepository.findOne(id);
    }
    
    /**
     * 根据账号查询用户
     * @param account
     * @return
     */
    public SysUser queryByAccount(String account) {
	return sysUserRepository.findByAccount(account);
    }
    
    /**
     * 根据email查询用户
     * @param email
     * @return
     */
    public SysUser queryByEmail(String email) {
	return sysUserRepository.findByEmail(email);
    }
    
    /**
     * 根据phone查询用户
     * @param phone
     * @return
     */
    public SysUser queryByPhone(String phone) {
	return sysUserRepository.findByPhone(phone);
    }
    
    public List<SysUser> queryByMap(Map<String, Object> params) {
	return sysUserRepository.findAll(new SimpleSpecification<SysUser>(params, SysUser.class));
    }
    
    public SysUser queryOne(String username) {
	SysUser user;
	if((user=queryByAccount(username))!=null) {
	    return user;
	} else if((user=queryByEmail(username))!=null) {
	    return user;
	} else if((user=queryByPhone(username))!=null) {
	    return user;
	} 
	return null;
    }
    
    public List<String> queryPermissionByUserId(Long userId) {
	return sysAuthorizeService.queryPermissionByUserId(userId);
    }
}
